package com.jhj.provider.resume.controller;

import java.io.IOException;
import java.io.UnsupportedEncodingException;
import java.util.HashMap;
import java.util.List;
import java.util.Map;

import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestMethod;
import org.springframework.web.bind.annotation.RequestParam;
import org.springframework.web.bind.annotation.RestController;
import org.springframework.web.multipart.MultipartFile;

import com.fasterxml.jackson.core.JsonParseException;
import com.fasterxml.jackson.databind.JsonMappingException;
import com.fasterxml.jackson.databind.ObjectMapper;
import com.jhj.provider.resume.po.b.model.Resume;
import com.jhj.provider.resume.po.b.model.ResumeResource;
import com.jhj.provider.resume.po.b.model.ResumeScore;
import com.jhj.provider.resume.service.ResumeLogService;
import com.jhj.provider.resume.service.ResumeResourceService;
import com.jhj.provider.resume.service.ResumeScoreService;
import com.jhj.provider.resume.service.ResumeService;
import com.jhj.provider.resume.utils.Constants;
import com.jhj.utils.AppResultData;
import com.jhj.utils.ImgServerUtil;
import com.jhj.utils.QiNiuFileUtil;
import com.jhj.utils.TimeStampUtil;
import com.qiniu.util.Auth;

/**
 *
 */
@RestController
public class ResumeResourceController {

	@Autowired
	ResumeService resumeService;

	@Autowired
	ResumeScoreService resumeScoreService;

	@Autowired
	ResumeLogService resumeLogService;

	@Autowired
	ResumeResourceService resumeResourceService;

	@Value("${img.host}")
	private String imgHost;

	@Value("${video.accessKey}")
	private String videoAccessKey;

	@Value("${video.SecretKey}")
	private String videoSecretKey;

	/**
	 * 上传图片接口
	 * 
	 * @param resumeNo
	 * @param resourceType
	 * @param canMulti
	 *            0 = 仅允许一张 1 = 允许多张
	 * @param imgs
	 * @return
	 * @throws JsonParseException
	 * @throws JsonMappingException
	 * @throws IOException
	 */
	@SuppressWarnings("unchecked")
	@RequestMapping(value = "/api/resume/upload_img.json", method = RequestMethod.POST)
	public AppResultData<Object> uploadImg(@RequestParam("resumeNo") String resumeNo,
			@RequestParam("resourceType") String resourceType,
			@RequestParam(value = "canMulti", required = false, defaultValue = "0") Integer canMulti,
			@RequestParam(value = "imgs", required = false) MultipartFile[] imgs)
			throws JsonParseException, JsonMappingException, IOException {
		AppResultData<Object> result = new AppResultData<Object>(Constants.SUCCESS_0, "ok", "");

		// 校验1. 判断人才是否存在
		Resume searchVo = new Resume();
		searchVo.setResumeNo(resumeNo);
		Resume resume = resumeService.selectOne(searchVo);
		if (resume == null) {
			result.setStatus(Constants.ERROR_999);
			result.setMsg("人才信息不存在");
			return result;
		}
		Integer resumeId = resume.getResumeId();

		if (canMulti.equals(0)) {
			ResumeResource resourceSearchVo = new ResumeResource();
			resourceSearchVo.setResumeId(resumeId);
			resourceSearchVo.setResourceType(resourceType);
			resumeResourceService.delete(resourceSearchVo);
		}

		// 处理上传图片
		for (int i = 0; i < imgs.length; i++) {
			String url = imgHost + "/upload/";
			String fileName = imgs[i].getOriginalFilename();
			String fileType = fileName.substring(fileName.lastIndexOf(".") + 1);
			fileType = fileType.toLowerCase();
			String sendResult = ImgServerUtil.sendPostBytes(url, imgs[i].getBytes(), fileType);

			ObjectMapper mapper = new ObjectMapper();
			HashMap<String, Object> o = mapper.readValue(sendResult, HashMap.class);
			// String ret = o.get("ret").toString();
			HashMap<String, String> info = (HashMap<String, String>) o.get("info");
			String imgUrl = imgHost + "/" + info.get("md5").toString();

			ResumeResource record = resumeResourceService.initPo(new ResumeResource());
			record.setResumeId(resumeId);
			record.setResumeNo(resumeNo);
			record.setResourceType(resourceType);
			record.setResourceUrl(imgUrl);
			record.setAddTime(TimeStampUtil.getNowSecond().intValue());
			resumeResourceService.insert(record);
		}

		// 如果为头像上传，则把完整度和分数都增加
		if (resourceType.equals(Constants.RES_RESUME_HEAD_IMG)) {
			// 信息完整度
			Integer totalComplete = resumeScoreService.getTotalComplete(resume);
			resume.setTotalComplete(totalComplete);

			Integer totalScore = resume.getTotalScore();
			totalScore = totalScore + Constants.SCORE_COMPLETE_HEADIMG;
			resume.setTotalScore(totalScore);

			resume.setUpdateTime(TimeStampUtil.getNowSecond().intValue());
			resumeService.update(resume);

			// 鲜活度明细
			ResumeScore resumeScoreSearchVo = new ResumeScore();
			resumeScoreSearchVo.setResumeId(resumeId);
			resumeScoreSearchVo.setAction(Constants.ACTION_PLUS_RESUME_HEADIMG);
			List<ResumeScore> list = resumeScoreService.selectBySearchVo(resumeScoreSearchVo, "");
			if (list.isEmpty()) {
				ResumeScore resumeScore = resumeScoreService.initPo(new ResumeScore());
				resumeScore.setResumeId(resumeId);
				resumeScore.setResumeNo(resumeNo);
				resumeScore.setActionType(0);
				resumeScore.setAction(Constants.ACTION_PLUS_RESUME_HEADIMG);
				resumeScore.setScore(Constants.SCORE_COMPLETE_HEADIMG);
				resumeScore.setRemark("上传头像增加" + String.valueOf(Constants.SCORE_COMPLETE_HEADIMG));
				resumeScore.setAddTime(TimeStampUtil.getNowSecond().intValue());
				resumeScoreService.insert(resumeScore);
			}
		}

		Map<String, Object> data = new HashMap<String, Object>();
		data.put("resumeId", resumeId);
		data.put("resumeNo", resumeNo);

		result.setData(data);
		return result;
	}

	@RequestMapping(value = "/api/resume/upload_del.json", method = RequestMethod.POST)
	public AppResultData<Object> updateDelete(@RequestParam("resumeNo") String resumeNo,
			@RequestParam("resourceType") String resourceType, @RequestParam("resourceId") Integer resourceId) {
		AppResultData<Object> result = new AppResultData<Object>(Constants.SUCCESS_0, "ok", "");

		// 校验1. 判断人才是否存在
		Resume searchVo = new Resume();
		searchVo.setResumeNo(resumeNo);
		Resume resume = resumeService.selectOne(searchVo);
		if (resume == null) {
			result.setStatus(Constants.ERROR_999);
			result.setMsg("人才信息不存在");
			return result;
		}
		Integer resumeId = resume.getResumeId();

		ResumeResource resourceSearchVo = new ResumeResource();
		resourceSearchVo.setResumeId(resumeId);
		resourceSearchVo.setResourceType(resourceType);
		resourceSearchVo.setResourceId(resourceId);
		resumeResourceService.delete(resourceSearchVo);

		Map<String, Object> data = new HashMap<String, Object>();
		data.put("resumeId", resumeId);
		data.put("resumeNo", resumeNo);

		result.setData(data);
		return result;
	}

	@RequestMapping(value = "/api/resume/upload_video.json", method = RequestMethod.POST)
	public AppResultData<Object> updateVideo(@RequestParam("resumeNo") String resumeNo,
			@RequestParam("videoUrl") String videoUrl) {
		AppResultData<Object> result = new AppResultData<Object>(Constants.SUCCESS_0, "ok", "");

		// 校验1. 判断人才是否存在
		Resume searchVo = new Resume();
		searchVo.setResumeNo(resumeNo);
		Resume resume = resumeService.selectOne(searchVo);
		if (resume == null) {
			result.setStatus(Constants.ERROR_999);
			result.setMsg("人才信息不存在");
			return result;
		}
		Integer resumeId = resume.getResumeId();

		ResumeResource resourceSearchVo = new ResumeResource();
		resourceSearchVo.setResumeId(resumeId);
		resourceSearchVo.setResourceType(Constants.RES_RESUME_VIDEO);
		ResumeResource record = resumeResourceService.selectOne(resourceSearchVo);

		if (record == null)
			record = resumeResourceService.initPo(new ResumeResource());

		record.setResumeId(resumeId);
		record.setResumeNo(resumeNo);
		record.setResourceType(Constants.RES_RESUME_VIDEO);
		record.setResourceUrl(videoUrl);
		record.setAddTime(TimeStampUtil.getNowSecond().intValue());

		if (record.getResourceId() > 0) {
			resumeResourceService.update(record);
		} else {
			resumeResourceService.insert(record);
		}

		Map<String, Object> data = new HashMap<String, Object>();
		data.put("resumeId", resumeId);
		data.put("resumeNo", resumeNo);

		result.setData(data);
		return result;
	}

	/**
	 * @return upToken
	 * 
	 * */
	@RequestMapping(value = "/api/resume/up_token.json", method = RequestMethod.GET)
	public AppResultData<Object> upToken()
			throws UnsupportedEncodingException {
		AppResultData<Object> result = new AppResultData<Object>(Constants.SUCCESS_0, "ok", "");
		String upToken = QiNiuFileUtil.getUpToken();
		result.setData(upToken);
		return result;
	}

	/**
	 * 七牛云下载token
	 * 
	 * @param videoUrl
	 * @return result
	 * @throws UnsupportedEncodingException
	 */
	@RequestMapping(value = "/api/resume/download_token.json", method = RequestMethod.GET)
	public AppResultData<Object> getDownLoadToken(@RequestParam("videoUrl") String videoUrl)
			throws UnsupportedEncodingException {
		AppResultData<Object> result = new AppResultData<Object>(Constants.SUCCESS_0, "ok", "");

		// String fileName = "七牛/云存储/qiniu.jpg";
		// String domainOfBucket = "http://devtools.qiniu.com";
		// String encodedFileName = URLEncoder.encode(fileName, "utf-8");
		// String publicUrl = String.format("%s/%s", domainOfBucket, encodedFileName);

		Auth auth = Auth.create(videoAccessKey, videoSecretKey);
		long expireInSeconds = 7200;// 2小时，可以自定义链接过期时间
		String finalUrl = auth.privateDownloadUrl(videoUrl, expireInSeconds);
		System.out.println(finalUrl);

		result.setData(finalUrl);

		return result;
	}
}